package com.programmercarl.backtracking;

import java.util.*;

/**
 * https://leetcode.cn/problems/combination-sum/description/
 * <p>
 * 组合总和
 *
 * @author yulongtian
 * @create 2025-01-06 21:35
 */
public class Test04 {
    public static void main(String[] args) {
        Test04 test04 = new Test04();
        int[] arr = {2, 3, 6, 7};
        int target = 7;
        List<List<Integer>> lists = test04.combinationSum(arr, target);
        System.out.println(lists);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Deque<Integer> path = new ArrayDeque<>();
        backtrack(candidates, target, 0, 0, res, path);
        return res;
    }

    private void backtrack(int[] candidates, int target, int start, int sum, List<List<Integer>> res, Deque<Integer> path) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (sum > target) {
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            path.push(candidates[i]);
            backtrack(candidates, target, i, sum + candidates[i], res, path);
            path.pop();
        }
    }


}
